<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图像标注工具</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            padding: 20px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100vh;
        }
        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 20px;
        }
        .container {
            display: flex;
            justify-content: center;
            align-items: flex-start;
            width: 100%;
        }
        .image-container {
            flex: 1;
            margin-right: 20px;
            max-width: 80%;
        }
        canvas {
            cursor: crosshair;
            display: block;
            margin: 0 auto;
        }
        .input-container {
            flex: 1;
            text-align: center;
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        .button-container {
            margin-top: 20px;
            display: flex;
            gap: 10px;
        }
        .button-container button {
            padding: 10px 20px;
            background-color: #28a745;
            color: white;
            border: none;
            cursor: pointer;
            font-size: 16px;
            border-radius: 0;
        }
        .button-container button:hover {
            background-color: #218838;
        }
        .input-container input {
            margin: 5px;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
            width: 45%;
            font-size: 14px;
            box-sizing: border-box;
        }
        .input-row {
            display: flex;
            justify-content: center;
            width: 100%;
        }
    </style>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

</head>
<body>
    <div class="container">
        <div class="image-container">
            <canvas id="canvas"></canvas>
        </div>
        <div class="input-container" id="inputContainer">
            <p>在图像上绘制矩形并在下面输入名称：</p>
            <div class="button-container">
                <button id="undoBtn">撤销</button>
                <button id="exportBtn">导出数据</button>
            </div>
        </div>
    </div>
    <script>
        const API_BASE = '/api';

        // 获取画布和上下文
        const canvas = document.getElementById('canvas');
        const ctx = canvas.getContext('2d');

        let img;
        const url = new URL(window.location.href);
        const monitorId = url.searchParams.get("monitorId");

        // 获取图片 URL 的函数
        async function fetchImageUrl() {
            try {


                // 添加请求头，例如 Authorization
                const img = await axios.get(`${API_BASE}/setImgData?monitorId=${monitorId}`, {
                    headers: {
                        authorization: 'aaec1f392fb6831833f7f3b70249361e' // 替换为你的认证信息
                    }
                });

                // console.log('API 返回数据:', img.data.data); // 打印返回的数据以便调试
                return img.data.data.image_path; // 假设返回的数据中包含 imageUrl 字段
            } catch (error) {
                console.error('获取图片失败:', error);
                return null;
            }
        }

        // 加载图片
        async function loadImage() {
            const imageUrl = await fetchImageUrl();
            if (!imageUrl) {
                alert('无法加载图片');
                return;
            }

            img = new Image();
            img.src = imageUrl;
            img.onload = () => {
                // 动态调整 canvas 大小
                const maxWidth = document.querySelector('.image-container').clientWidth * 1.5; // 增加宽度比例
                const maxHeight = window.innerHeight * 1.0; // 增加高度比例
                const scale = Math.min(maxWidth / img.width, maxHeight / img.height);
                canvas.width = img.width * scale;
                canvas.height = img.height * scale;

                // 绘制图片到 canvas
                ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
            };
        }

        // 调用加载图片函数
        loadImage();

        // 矩形绘制相关变量
        let isDrawing = false;
        let startX, startY, endX, endY;
        const rectangles = []; // 存储所有矩形信息

        // 鼠标事件监听
        canvas.addEventListener('mousedown', (e) => {
            isDrawing = true;
            startX = e.offsetX;
            startY = e.offsetY;
        });

        canvas.addEventListener('mousemove', (e) => {
            if (!isDrawing) return;
            endX = e.offsetX;
            endY = e.offsetY;
            drawRectangles(); // 重绘画布
            ctx.strokeStyle = 'red';
            ctx.strokeRect(startX, startY, endX - startX, endY - startY); // 绘制当前矩形
        });

        canvas.addEventListener('mouseup', () => {
            if (!isDrawing) return;
            isDrawing = false;

            // 计算矩形的四个顶点坐标（基于原图比例）
            const scaleX = img.width / canvas.width;
            const scaleY = img.height / canvas.height;
            const rect = {
                topLeft: [startX * scaleX, startY * scaleY],
                topRight: [endX * scaleX, startY * scaleY],
                bottomLeft: [startX * scaleX, endY * scaleY],
                bottomRight: [endX * scaleX, endY * scaleY],
                name: ''
            };
            rectangles.push(rect); // 保存矩形信息
            addInputField(); // 添加输入框
        });

        // 添加输入框
        function addInputField() {
            const inputContainer = document.getElementById('inputContainer');
            const inputRow = document.createElement('div');
            inputRow.className = 'input-row';

            const input = document.createElement('input');
            input.type = 'text';
            input.placeholder = `输入矩形 ${rectangles.length} 的名称`;

            // 将输入框的值绑定到当前矩形信息
            const currentRectIndex = rectangles.length - 1;
            input.addEventListener('input', () => {
                rectangles[currentRectIndex].name = input.value;
            });

            inputRow.appendChild(input);

            // 如果当前行已有一个输入框，则添加到同一行
            if (inputContainer.lastChild && inputContainer.lastChild.className === 'input-row' && inputContainer.lastChild.childElementCount < 2) {
                inputContainer.lastChild.appendChild(input);
            } else {
                inputContainer.appendChild(inputRow);
            }
        }

        // 撤销功能
        document.getElementById('undoBtn').addEventListener('click', () => {
            if (rectangles.length > 0) {
                rectangles.pop(); // 移除最后一个矩形
                const inputContainer = document.getElementById('inputContainer');
                const lastInputRow = inputContainer.querySelector('.input-row:last-child');
                if (lastInputRow) {
                    lastInputRow.removeChild(lastInputRow.lastChild); // 移除最后一个输入框
                    if (lastInputRow.childElementCount === 0) {
                        inputContainer.removeChild(lastInputRow); // 如果行为空，移除行
                    }
                }
                drawRectangles(); // 重绘画布
            }
        });

        // 重绘画布（包括图片和所有矩形）
        function drawRectangles() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
            rectangles.forEach(rect => {
                // 将原图坐标映射回 canvas 坐标
                const scaleX = canvas.width / img.width;
                const scaleY = canvas.height / img.height;
                ctx.strokeStyle = 'blue';
                ctx.beginPath();
                ctx.moveTo(rect.topLeft[0] * scaleX, rect.topLeft[1] * scaleY);
                ctx.lineTo(rect.topRight[0] * scaleX, rect.topRight[1] * scaleY);
                ctx.lineTo(rect.bottomRight[0] * scaleX, rect.bottomRight[1] * scaleY);
                ctx.lineTo(rect.bottomLeft[0] * scaleX, rect.bottomLeft[1] * scaleY);
                ctx.closePath();
                ctx.stroke();
            });
        }

        // 导出数据
        document.getElementById('exportBtn').addEventListener('click', async () => {
            const output = rectangles.map(rect => ({
                [rect.name]: [
                    rect.topLeft.map(coord => parseFloat(coord.toFixed(2))),
                    rect.topRight.map(coord => parseFloat(coord.toFixed(2))),
                    rect.bottomLeft.map(coord => parseFloat(coord.toFixed(2))),
                    rect.bottomRight.map(coord => parseFloat(coord.toFixed(2)))
                ]
            }));
            const data = JSON.stringify(output, null, 0);

            const res = {
                "monitorId": monitorId,
                data
            };
            console.log(res);

            await axios.post(`${API_BASE}/setIndicator`, res, {
                headers: {
                    authorization: 'aaec1f392fb6831833f7f3b70249361e'
                }
            });
        });
    </script>
</body>
</html>